const express = require('express')
const fs = require('fs');
let program = require('commander');
program
    .version('0.0.1')
    .option('-pp, --picture', 'Add picture')
    .option('-vp, --video', 'Add video')
    .parse()
const options = program.opts();

if (!options.picture && !program.opts().video) {
    console.log('请填写启动参数');
    return
}
let basePath = program.args[0]
let videoPath = program.args[1]
const app = express()
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

app.listen(3000, () => console.log('Example app listening on port 3000!'))

app.use('/', express.static('static'))
app.use('/', express.static(basePath))
app.use('/', express.static(videoPath))

app.get('/home', (req, res) => res.send(fileDisplay(basePath)))

app.get('/video', function (req, res) {
    let files = fs.readdirSync(videoPath);
    files = files
        .filter(fileName => fileName.endsWith(".mp4"))
    res.send(randomList(files, 10))
})
app.get('/book', function (req, res) {
    let filePath = req.query.name
    let files = fs.readdirSync(basePath + filePath);
    files = files
        .filter(fileName => fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".bmp") || fileName.endsWith(".png"))
        .map(T => {
            let path = {}
            path.path = filePath
            path.name = T
            return path
        })
    res.send(files)
})

function fileDisplay(filePath) {
    let files = fs.readdirSync(filePath);
    let fileHeader = []
    files.forEach(T => {
        let stat = fs.lstatSync(filePath + T);
        let path = {}
        if (stat.isDirectory()) {
            let result = fs.readdirSync(filePath + T).filter(E => E.endsWith(".jpg"));
            if (result.length > 0) {
                path.path = T
                path.name = result[0]
                fileHeader.push(path)
            }
        }
    })
    return randomList(fileHeader, 10)
}


function randomList(arr, limit, result) {
    if (!result) {
        result = []
    }
    let index = Math.floor(Math.random() * arr.length)
    result.push(arr[index])
    arr.splice(index, 1)
    if (arr.length === 0 || result.length >= limit) {
        return result
    }
    return randomList(arr, limit, result);
}